package com.wstuo.common.config.onlinelog.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.onlinelog.dao.IUserOnlineLogDAO;
import com.wstuo.common.config.onlinelog.dto.UserOnlineLogDTO;
import com.wstuo.common.config.onlinelog.dto.UserOnlineLogQueryDTO;
import com.wstuo.common.config.onlinelog.entity.UserOnlineLog;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.security.dao.IUserDAO;
import com.wstuo.common.security.entity.User;
import com.wstuo.common.security.utils.AppConfigUtils;
import com.wstuo.common.util.LogUtils;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;
import com.wstuo.multitenancy.TenantIdResolver;

/**
 * 用户在线日志业务类.
 * @author QXY date 2011-02-11
 *
 */
public class UserOnlineLogService implements IUserOnlineLogService {

	@Autowired
	private IUserOnlineLogDAO useronlinelogDAO;
	
	@Autowired
	private IUserDAO userDAO;
//	@Autowired
//	private ICache cacheService;
	
	/**
	 * 返回公司编号.
	 * @return Long
	 */
	@Transactional
	public Long findCompanyNoByUserName(String userName){
		Long companyNo = null;
		//根据用户名查找
		User u=userDAO.findUniqueBy("loginName",userName);
		
		if(u!=null && u.getCompanyNo()!=null){
			companyNo = u.getCompanyNo();
		}
		return companyNo;
	}


	/**
	 * 返回用户名.
	 * @return String
	 */
	public String getUserName(String sessionId){
		String userName = null;
		UserOnlineLog entity = useronlinelogDAO.findBySessionId(sessionId);
		if(entity!=null){
			userName = entity.getUserName();
		}
		return userName;
	}
	

	/**
	 * 添加用户在线记录
	 * @param dto 
	 */
	@Transactional
	public void online(UserOnlineLogDTO dto) {

		//Object cacheValue = cacheService.getValue(dto.getUserName());
		String tenantId = TenantIdResolver.getInstance().getDefaultTenantId();
	//	if(cacheValue!=null){
	//		tenantId = cacheValue.toString();
	//	}
		
		UserOnlineLog entity = new UserOnlineLog();
		UserOnlineLogDTO.dto2entity(dto, entity);
		
		//在线记录
		if(entity.getUserName()!=null){
			User usr=userDAO.findUniqueBy("loginName", entity.getUserName());
			if(usr!=null){
				entity.setUserFullName(usr.getFullName());
				boolean result = userDAO.isTc(usr.getRoles());
				String userRole = UserOnlineUtil.ENDUSER;
				if(result){
					userRole = UserOnlineUtil.TECHNICIAN; 
				}
				UserOnlineLog userOnlineLog = new UserOnlineLog();
				userOnlineLog.setUserName(dto.getUserName());
				userOnlineLog.setUserFullName(usr.getFullName());
				userOnlineLog.setSessionId(dto.getSessionId());
				
				UserOnlineUtil.getInstance().put(tenantId, userOnlineLog, userRole);
			}
		}
		
		String filePath =  AppConfigUtils.getInstance().getOnlineLogPath()+"/userOnlineLog.csv";
		String date = TimeUtils.format(new Date(), TimeUtils.DATETIME_PATTERN);
		Logger logger =  LogUtils.getOnlineLogger(filePath, dto.getUserName(), "online", date, dto.getSessionId(), "userOnlineLog"+tenantId);
		      logger.log(Level.INFO, "");
	}
	/**
	 * 更新用户在线记录
	 * @param logs 
	 */
	@Transactional
	public void updateOnline(List<UserOnlineLogDTO> dtos){
		List<UserOnlineLog> userOnlineLogs = new ArrayList<UserOnlineLog>();
		for(UserOnlineLogDTO dto : dtos){
			UserOnlineLog entity = new UserOnlineLog();
			UserOnlineLogDTO.dto2entity(dto, entity);
			entity.setOfflineTime(new Date());//设置下线时间
			userOnlineLogs.add(entity);
		}
		useronlinelogDAO.mergeAll(userOnlineLogs);
	}

	/**
	 * 添加用户离线记录.
	 * @param sessionId 会话编号
	 */
	@Transactional
	public void offline(String sessionId,String loginName) {

		//Object cacheValue = cacheService.getValue(loginName);
		String tenantId = TenantIdResolver.getInstance().getDefaultTenantId();
		//if(cacheValue!=null){
		//	tenantId = cacheValue.toString();
		//}
		
		//在线记录
		if(StringUtils.hasLength(loginName)){
			User usr=userDAO.findUniqueBy("loginName", loginName);
			if(usr!=null){
				boolean result = userDAO.isTc(usr.getRoles());
				String userRole = UserOnlineUtil.ENDUSER;
				if(result){
					userRole = UserOnlineUtil.TECHNICIAN; 
				}
				UserOnlineLog userOnlineLog = new UserOnlineLog();
				userOnlineLog.setUserName(loginName);
				userOnlineLog.setUserFullName(usr.getFullName());
				userOnlineLog.setSessionId(sessionId);
				boolean removeResult = UserOnlineUtil.getInstance().remove(tenantId, userOnlineLog, userRole);
				//由于用户中途可能会更换角色，所以多加此判断，确保在线用户更新成功
				if(!removeResult){
					if(userRole.equals(UserOnlineUtil.ENDUSER)){
						userRole =UserOnlineUtil.TECHNICIAN;
					}else{
						userRole = UserOnlineUtil.ENDUSER;
					}
					UserOnlineUtil.getInstance().remove(tenantId, userOnlineLog, userRole);
				}
			}
		}
		
		String filePath =  AppConfigUtils.getInstance().getOnlineLogPath()+"/userOnlineLog.csv";
		String date = TimeUtils.format(new Date(), TimeUtils.DATETIME_PATTERN);
		Logger logger = LogUtils.getOnlineLogger(filePath, loginName, "offline", date , sessionId, "userOnlineLog"+tenantId);
		logger.log(Level.INFO, "");
	}

	/**
	 * 分页查询用户在线日志.
	 * @param useronlinelogQueryDTO 查询DTO
	 * @param start 开始数据行
	 * @param limit 每页数据条数
	 * @return PageDTO 分页数据
	 */
	@SuppressWarnings("unchecked")
	public PageDTO findUserOnlineByPager(UserOnlineLogQueryDTO useronlinelogQueryDTO,
			int start, int limit) {
		PageDTO p = useronlinelogDAO.findPager(useronlinelogQueryDTO, start,limit);
		List<UserOnlineLog> useronlinelog = (List<UserOnlineLog>) p.getData();
		List<UserOnlineLogDTO> dtos = new ArrayList<UserOnlineLogDTO>(
				useronlinelog.size());
		for (UserOnlineLog entity : useronlinelog) {
			UserOnlineLogDTO dto = new UserOnlineLogDTO();
			UserOnlineLogDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}
		p.setData(dtos);

		return p;
	}

}